package com.hujing.sqlinjection.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hujing.sqlinjection.mapper.CityMenuMapper;
import com.hujing.sqlinjection.entity.CityMenu;
import com.hujing.sqlinjection.service.CityMenuService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 城市关联菜单(CityMenu)
 *
 * @author hujing
 * @since 2025-04-20 10:39:37
 */
@Service("cityMenuService")
public class CityMenuServiceImpl extends ServiceImpl<CityMenuMapper, CityMenu> implements CityMenuService {
    
    @Autowired
    private DataSource dataSource;

    private static final Logger log = LoggerFactory.getLogger(CityMenuServiceImpl.class);

    // 测试sql注入
    @Override
    public Integer sqlInjectTest(String cityName) {
        //查询名字为name的城市
        String sql = "select count(*) from city_menu where city='" + cityName + "'";
        //执行查询
        return baseMapper.queryBySql(sql);
    }

    // 防止sql注入
    public Integer forbittenSqlInjectTest(String cityName) {
//        String sql = "select count(*) from city_menu where city = ?";
//        List<Integer> list = jdbcTemplate.query(sql, new Object[]{cityName}, (rs, rowNum) -> rs.getInt("count(*)"));
//        return list.get(0);

        String sql = "select * from city_menu where city = ?";
        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, cityName);
            try (ResultSet resultSet = ps.executeQuery()) {
                if (resultSet.next()){
                    // 处理查询结果
                    log.info("查询结果集：{}", resultSet.getInt(1));
                }else{
                    log.info("查询结果集为空");
                }
            }
        } catch (SQLException e) {
            // 处理数据库异常
            e.printStackTrace();
        }

        return 0;
    }
}

